package com.vhall.component.service.room.event.handler.record;

import com.alibaba.fastjson.JSONObject;
import com.vhall.component.dao.room.RecordOfRoomMapper;
import com.vhall.component.entity.record.RecordEntity;
import com.vhall.component.plugin.common.constant.HttpConstant;
import com.vhall.component.plugin.core.service.PaasService;
import com.vhall.component.service.room.concant.RoomConstant;
import com.vhall.component.service.room.event.handler.AbstractEventHandler;
import com.vhall.component.service.room.event.handler.EventHandlerType;
import com.vhall.component.service.room.event.handler.RedirectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

import static com.vhall.component.service.room.event.EventConstant.ALL_TRANSCODE_COMPLETE;


/**
 * @author jingwen.li
 * @date 2023/2/16
 */
@Slf4j
@Component
@EventHandlerType(ALL_TRANSCODE_COMPLETE)
public class AllTranscodeCompleteEventHandler extends AbstractEventHandler {
    @Autowired
    private RedirectUtil redirectUtil;
    @Value("${old.callback.record.url}")
    private String callbackUrl;
    @Autowired
    private RecordOfRoomMapper recordOfRoomMapper;
    @Autowired
    private PaasService paasService;

    @Override
    public void handle(Map<String, Object> callBack) {
//        redirectUtil.redirect(callbackUrl, callBack);
        log.info("收到视频的全部清晰度全部格式都转码完成事件：{}, 事件详情：{}", ALL_TRANSCODE_COMPLETE, callBack);
        String vodId = (String) callBack.get(RoomConstant.VOD_ID);
        RecordEntity recordEntity = recordOfRoomMapper.findByVodId(vodId);
        if (recordEntity != null) {
            recordEntity.setTranscodeStatus(Integer.valueOf(String.valueOf(callBack.get("status"))));
            recordEntity.setUpdatedAt(LocalDateTime.now());
            recordOfRoomMapper.updateById(recordEntity);
            JSONObject vodInfo = paasService.getRecordInfo(vodId);
            if (vodInfo.getInteger(HttpConstant.CODE) != HttpConstant.SUCCESS_CODE) {
                log.error("获取视频详细信息错误");
            } else {
                JSONObject data = vodInfo.getJSONObject(HttpConstant.DATA);
                JSONObject vod = data.getJSONObject("vod_info");

                recordEntity.setDuration(vod.getInteger("duration"));
                recordEntity.setUpdatedAt(LocalDateTime.now());
                recordOfRoomMapper.updateById(recordEntity);
            }
        }
    }
}
